from flask import Flask, request, render_template, jsonify, session
from flask import redirect, url_for, json
from config import DevConfig
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import exists
from werkzeug.utils import secure_filename
import datetime
import os
from werkzeug.security import generate_password_hash, check_password_hash  # 加密

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])  # 文件允许上传格式
UPLOAD_FOLDER = 'static/uploads/'  # 文件下载路径
app = Flask(__name__)
app.config.from_object(DevConfig)
db = SQLAlchemy(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER  # 设置文件下载路径
app.config['SECRET_KEY'] = '123456'
# 数据库模型
from models import User, Book, Bookrack


def allowed_file(filename):  # 通过将文件名分段的方式查询文件格式是否在允许上传格式范围之内
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


# 首页
@app.route('/', methods=['GET'])
def home():
    return redirect(url_for('index'))  # 重定向


@app.route('/index/', methods=['GET'])
def index():
    books = Book.query.limit(15)
    if session:
        nickname = session['nickname']
        user_image = session['user_image']
        return render_template('index.html', nickname=nickname, user_image=user_image, books=books)
    else:

        return render_template('index.html', books=books)


# 获取图书列表 !!!
@app.route('/bookList/<page>', methods=['GET'])
def bookList(page):
    # sql = "select * from book limit 15, 30"
    books = []
    # query = db.session.execute(sql)
    query = db.session.query(Book)
    for book in query.order_by(Book.id).offset(int(page)*15).limit(15):
        books.append(book.getDict())

    return jsonify({'books': books})


# 用户注册

@app.route('/regist/', methods=['GET', 'POST'])
def regist():
    if request.method == 'GET':
        return render_template('regist.html')
    else:
        account = request.form['account']
        nickname = request.form['nickname']
        paw = generate_password_hash(request.form['paw'])  # md5哈希加密
        pic = request.files['pic']
        if allowed_file(pic.filename) == False:
            return jsonify({'message': '图片格式不对', 'code': 0})
        else:
            # 查找当前账户是否存在
            u = db.session.query(exists().where(
                User.account == account)).scalar()
            if u:
                return jsonify({'message': '账户已存在', 'code': 0})
            else:
                ext = secure_filename(pic.filename).rsplit('.', 1)[1]  # 获取文件后缀
                filename = 'user_'+account+'.'+ext  # 修改了上传的文件名
                # pic.save('static/uploading/user_images/'+account+'.jpg')
                img_src = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                pic.save(img_src)

                user = User(account=account, nickname=nickname,
                            password=paw, user_image='/'+img_src)
                db.session.add(user)
                db.session.commit()
                return jsonify({'message': '注册成功', 'code': 1})

# 用户登录


@app.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template('login.html')
    else:
        account = request.form['account']
        u = db.session.query(exists().where(User.account == account)).scalar()
        if u == False:
            return jsonify({'message': '账户不存在', 'code': 0})
        else:
            paw = request.form['paw']
            user_paw = db.session.query(User.password).filter(
                User.account == account).one()[0]

            if check_password_hash(user_paw, paw) == False:
                return jsonify({'message': '密码错误', 'code': 0})
            else:
                nickname = db.session.query(User.nickname).filter(
                    User.account == account).one()[0]
                user_image = db.session.query(User.user_image).filter(
                    User.account == account).one()[0]
                session['account'] = account
                session['nickname'] = nickname
                session['user_image'] = user_image

                return jsonify({'message': '登录成功', 'code': 1})


# 用户中心
@app.route('/userInfo/', methods=['GET'])
def userinfo():
    account = session['account']
    nickname = session['nickname']
    user_image = session['user_image']

    return render_template('user_info.html', account=account, nickname=nickname, user_image=user_image)

# 退出登陆


@app.route('/logout/', methods=['GET'])
def logout():
    session.pop('account', None)
    session.pop('nickname', None)
    session.pop('user_image', None)

    return redirect(url_for('index'))  # 重定向


# 忘记密码


@app.route('/forgetPW/', methods=['POSt', 'GET'])
def forgetPW():

    if request.method == 'GET':
        return render_template('forget_password.html')
    else:
        account = request.form['account']
        nickname = request.form['nickname']
        u = db.session.query(exists().where(User.account == account)).scalar()
        if u == True:
            user_nickname = db.session.query(User.nickname).filter(
                User.account == account).one()[0]
            if user_nickname == nickname:
                paw = generate_password_hash(request.form['paw'])  # md5哈希加密
                db.session.query(User).filter(
                    User.account == account).update({User.password: paw})
                db.session.commit()
                return jsonify({'message': '密码已修改', 'code': 1})
            else:
                return jsonify({'message': '昵称不匹配', 'code': 0})
        else:
            return jsonify({'message': '账户不存在', 'code': 0})


# 用户信息修改
@app.route('/userSet/', methods=['GET'])
def userSet():
    account = session['account']
    nickname = session['nickname']
    user_image = session['user_image']
    return render_template('user_set.html', account=account, nickname=nickname, user_image=user_image)

# 修改头像


@app.route('/setPic/', methods=['POST'])
def setPic():
    account = session['account']
    pic = request.files['pic']

    ext = secure_filename(pic.filename).rsplit('.', 1)[1]  # 获取文件后缀
    filename = 'user_'+account+'.'+ext  # 修改了上传的文件名

    img_src = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    pic.save(img_src)
    db.session.query(User).filter(
        User.account == account).update({User.user_image: '/'+img_src})
    db.session.commit()
    return jsonify({'message': '头像修改成功', 'code': 1})


# 修改昵称
@app.route('/setNickname/',methods=['POST'])
def setNickname():
    account = session['account']
    nickname = request.form['nickname']
    db.session.query(User).filter(User.account == account).update({User.nickname:nickname})
    db.session.commit()
    session['nickname'] = nickname
    return jsonify({'message':'昵称修改成功', 'code':1})


# 修改密码
@app.route('/setPW/',methods=['GET','POST'])
def setPW():
    account = session['account']
    if request.method == 'GET':
        return render_template('setPW.html',account=account)
    else:
        oldPW = request.form['oldPW']
        newPW = generate_password_hash(request.form['newPW'])  # md5哈希加密
        user_pw = db.session.query(User.password).filter(User.account == account).one()[0]
        if check_password_hash(user_pw, oldPW) == True:
            db.session.query(User).filter(User.account == account).update({User.password:newPW})
            db.session.commit()
            
            return jsonify({'message':'密码修改成功','code':1})
        else:
            return jsonify({'message':'原密码不正确','code':0})



# 图书管理
@app.route('/admin/', methods=['GET'])
def admin():

    books = Book.query.all()
    return render_template('admin/admin.html', books=books)

# 添加图书


@app.route('/addBook/', methods=['GET', 'POST'])
def addBook():
    if request.method == 'GET':

        return render_template('admin/add_book.html')
    else:

        bookID = request.form['bookID']
        bookName = '《'+request.form['bookName']+'》'
        author = request.form['author']
        publishing = request.form['publishing']
        u = db.session.query(exists().where(Book.bookID == bookID)).scalar()
        if u:
            return jsonify({'message': '书本已存在', 'code': 0})
        else:
            book = Book(bookID=bookID, bookName=bookName,
                        author=author, publishing=publishing)
            db.session.add(book)
            db.session.commit()
            return jsonify({'message': '添加成功', 'code': 1})


# 个根据bookID删除书本
@app.route('/adminDeleteBook/', methods=['POST'])
def adminDeleteBook():
    bookId = request.form['bookId']
    book = Book.query.filter_by(bookID=bookId).first()
    db.session.delete(book)
    db.session.commit()
    return jsonify({'message': '删除成功'})


# 书本详情
@app.route('/bookDetails/<bookId>', methods=['GET'])
def book_details(bookId):

    book = Book.query.filter_by(bookID=bookId).first()

    return render_template('book_details.html', book=book.getDict())


# 书架页面
@app.route('/myBookrack/', methods=['GET'])
def myBookrack():
    account = session['account']

    bookrack = Bookrack.query.filter_by(account=account).all()

    return render_template('bookrack.html', books=bookrack)


# 借阅图书
@app.route('/borrow/', methods=['POST'])
def borrow():
    account = session['account']
    bookID = request.form['bookId']
    bookName = request.form['bookName']
    u = db.session.query(exists().where(Bookrack.account == account).where(
        Bookrack.bookID == bookID)).scalar()
    if u == True:
        return jsonify({'message': '该书您已借阅过，还未还书', 'code': 0})
    else:
        bookrack = Bookrack(account=account, bookID=bookID, bookName=bookName)
        db.session.add(bookrack)
        db.session.commit()
        return jsonify({'message': '成功借阅书本ID:'+bookID, 'code': 1})


# 归还图书
@app.route('/giveBack/', methods=['POST'])
def giveBack():
    bookId = request.form['bookId']
    account = session['account']
    book = Bookrack.query.filter_by(account=account, bookID=bookId).first()
    db.session.delete(book)
    db.session.commit()
    return jsonify({'message': '归还成功'})


if __name__ == '__main__':
    app.run()
